package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.user.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zzy
 * @date 2022/7/28 10:24
 */

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {


    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //检测用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        Integer userId = user.getId();
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        Short operation = dto.getOperation();
        //判断操作类型
        if (operation == 0) {
            //关注列表添加记录
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString(), System.currentTimeMillis());
            //粉丝列表添加记录
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + articleId, userId.toString(), System.currentTimeMillis());
        } else if (operation == 1) {
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + articleId, userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
